from multiprocessing import Queue, Process, JoinableQueue
import time
import random


# 生产者
def producers(p, name, food):
    for i in range(1, 10):
        # 制作时间
        time.sleep(random.randint(3, 4))
        print(f"{name}做了{food}第{i}份")
        p.put(f"{food}")


# 消费者
def consumers(q, name):
    while True:
        food = q.get()
        # 消费时间
        time.sleep(random.randint(1, 2))
        print(f"{name}吃了{food}")
        q.task_done()  # 告诉队列已经拿走一个数据，并已经处理完


if __name__ == '__main__':
    q = JoinableQueue()
    p1 = Process(target=producers, args=(q, "小富贵", "蛋炒饭"))
    p2 = Process(target=producers, args=(q, "小红娘", "茶白道"))
    c1 = Process(target=consumers, args=(q, "唐僧"))
    c2 = Process(target=consumers, args=(q, "八戒"))

    p1.start()
    p2.start()

    # 消费者进程设置为守护进程
    c1.daemon = True
    c2.daemon = True

    c1.start()
    c2.start()

    # 生产者进程运行结束后再运行主进程
    p1.join()
    p2.join()

    q.join()  # 主进程死后，消费者进程设置为守护进程也跟着死亡
